package centerserver;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;

import pojo.OnlineSocket;
import log.MyLogger;
import thread.SocketThread;

public class Server implements Runnable {
	private Map<String, OnlineSocket> onlineUser;
	private ServerSocket server;
	
	public Server(ServerSocket server) {
		this.onlineUser = new Hashtable<String, OnlineSocket>();
		this.server = server;
	}
	
	public Map<String, OnlineSocket> getOnlineUser() {
		return onlineUser;
	}

	@Override
	public void run() {
		
//		if (server != null && !server.isClosed()) {
//			return;
//		}
		
		MyLogger.log("Server started!");
		
		while (true) {
			Socket socket = null;
			try {
				socket = server.accept();
			} catch (SocketException e) {
				MyLogger.log("Server closed");
				System.out.println("Server closed");
				break;
			} catch (IOException e) {
				e.printStackTrace();
				break;
			}
			
			if (socket == null) {
				continue;
			}
			
//			System.out.println("Accepted.");
			MyLogger.log("Server Accepted! One client connect to the server.");
			
			SocketThread socketThread = new SocketThread(socket, onlineUser);
			new Thread(socketThread).start();
		}
	}
	
	public void close() throws IOException {
		if (server != null && !server.isClosed()) {
			server.close();
		}
		
		Iterator<Map.Entry<String, OnlineSocket>> it = onlineUser.entrySet().iterator();
		
		while (it.hasNext()) {
			Map.Entry<String, OnlineSocket> entry = it.next();
			Socket userSocket = entry.getValue().getSocket();
			OutputStream userOut = entry.getValue().getOutputStream();
			
			if (userOut != null) {
				userOut.close();
			}
			
			if (userSocket != null) {
				userSocket.close();
			}
			
//			it.remove();
		}
		
		onlineUser.clear();
	}

}
